//
//  ReleaseStep3ViewController.m
//  Gunz
//
//  Created by Joggy on 16/4/16.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "ReleaseStep3ViewController.h"
#import "BarButtonView.h"
#import "FDAlertView.h"
#import "RBCustomDatePickerView.h"
#import "ReleaseStep4ViewController.h"
#import "QYNotice.h"
#import "Gunz-Swift.h"

@interface ReleaseStep3ViewController ()<sendTheValueDelegate, UIScrollViewDelegate, UITextFieldDelegate, UITextViewDelegate, QYPhotosDelegate> {
    
    QYPhotos *photosView;
    
}

@end

@implementation ReleaseStep3ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    subTaskArr = [[NSMutableArray alloc] initWithCapacity:0];
    [self prepareForNav];
    [self prepareForLayout];
    textBottom = 0;
    scrollOrigin = scroll.frame;
    [scroll addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEdit)]];
    scroll.delegate = self;
    photosView = [[QYPhotos alloc] init];
    [photosView setBarItemColor:CUSTOM_GREEN];
    [photosView setBarTintColor:[UIColor whiteColor]];
    [photosView setSelectNumber:1];
    photosView.delegate = self;
    subTaskDescri = [[NSMutableDictionary alloc] initWithCapacity:0];
    NSLog(@"%@", _data);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)prepareForNav {
    [super prepareForNav];
    self.title = @"任务发布-步骤3";
    //导航左按键
    UIImage *image = [UIImage imageNamed:@"all_back"];
    UIButton *leftBarButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBarButton.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    leftBarButton.layer.position = CGPointMake(22, 22);
    [leftBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [leftBarButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarButton];
}

- (void)prepareForLayout {
    [super prepareForLayout];
    scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [GZConst getScreenWidth], [GZConst getScreenHeight] - 64 - 56)];
    scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height + 1);
    scroll.delegate = self;
    [self.view addSubview:scroll];
    //底部按钮
    BarButtonView *barButton = [[BarButtonView alloc] initWithFrame:CGRectMake(0, [GZConst getScreenHeight] - 64 - BBViewHeight, [GZConst getScreenWidth], BBViewHeight) name:@"下一步"];
    [barButton.but addTarget:self action:@selector(nextStep) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:barButton];
    //标题lab
    UILabel *titleConfig = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 76, 17)];
    titleConfig.layer.position = CGPointMake([GZConst getScreenWidth]/2, 34);
    titleConfig.textColor = CUSTOM_GREEN;
    titleConfig.font = [UIFont systemFontOfSize:14];
    titleConfig.textAlignment = NSTextAlignmentCenter;
    titleConfig.text = @"任务详情";
    [scroll addSubview:titleConfig];
    //
    taskName = [[Step3InputField alloc] initWithTitle:@"任务名称:"];
    taskName.layer.position = CGPointMake([GZConst getScreenWidth]/2, 83);
    taskName.textField.delegate = self;
    [scroll addSubview:taskName];
    taskDescribe = [[Step3InputView alloc] initWithTitle:@"任务描述:"];
    taskDescribe.layer.position = CGPointMake([GZConst getScreenWidth]/2, taskName.frame.origin.y + taskName.frame.size.height + 5 + 30);
    taskDescribe.textView.tag = -1;
    taskDescribe.textView.delegate = self;
    [scroll addSubview:taskDescribe];
    taskLocation = [[Step3InputField alloc] initWithTitle:@"任务地点:"];
    taskLocation.layer.position = CGPointMake([GZConst getScreenWidth]/2, taskDescribe.frame.origin.y + taskDescribe.frame.size.height + 5 + 18);
    taskLocation.textField.delegate = self;
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 26, 36)];
    rightView.backgroundColor = [UIColor clearColor];
    UIImage *im = [UIImage imageNamed:@"main_location"];
    UIButton *taskLocaBut = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 14, (im.size.height/im.size.width)*14)];
    [taskLocaBut setImage:im forState:UIControlStateNormal];
    taskLocaBut.layer.position = CGPointMake(13, 18);
    [rightView addSubview:taskLocaBut];
    taskLocation.textField.rightView = rightView;
    taskLocation.textField.rightViewMode = UITextFieldViewModeAlways;
    [scroll addSubview:taskLocation];
    taskIcon = [[Step3Icon alloc] initWithTitle:@"任务图标:"];
    taskIcon.layer.position = CGPointMake([GZConst getScreenWidth]/2, taskLocation.frame.origin.y + taskLocation.frame.size.height + 30 + 5);
    [taskIcon.button addTarget:self action:@selector(selectPhotos) forControlEvents:UIControlEventTouchUpInside];
    [scroll addSubview:taskIcon];
    taskSignTime = [[Step3Time alloc] initWithTitle:@"报名时间:"];
    taskSignTime.layer.position = CGPointMake([GZConst getScreenWidth]/2, taskIcon.frame.origin.y + taskIcon.frame.size.height + 9 + 8);
    [taskSignTime.time addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
    [scroll addSubview:taskSignTime];
    taskBeginTime = [[Step3Time alloc] initWithTitle:@"开始时间:"];
    taskBeginTime.layer.position = CGPointMake([GZConst getScreenWidth]/2, taskSignTime.frame.origin.y + taskSignTime.frame.size.height + 9 + 8);
    [taskBeginTime.time addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
    [scroll addSubview:taskBeginTime];
    taskEndTime = [[Step3Time alloc] initWithTitle:@"截止时间:"];
    taskEndTime.layer.position = CGPointMake([GZConst getScreenWidth]/2, taskBeginTime.frame.origin.y + taskBeginTime.frame.size.height + 9 + 8);
    [taskEndTime.time addTarget:self action:@selector(butClick:) forControlEvents:UIControlEventTouchUpInside];
    [scroll addSubview:taskEndTime];
    subTaskNum = [[Step3SubTaskNum alloc] initWithTitle:@"子任务数:"];
    subTaskNum.layer.position = CGPointMake([GZConst getScreenWidth]/2, taskEndTime.frame.origin.y + taskEndTime.frame.size.height + 9 + 18);
    [subTaskNum.button addTarget:self action:@selector(selectSubTaskNum) forControlEvents:UIControlEventTouchUpInside];
    [scroll addSubview:subTaskNum];
    [self adjustScrollContent:subTaskNum.frame.origin.y + subTaskNum.frame.size.height];
}

#pragma 事件方法

- (void)selectPhotos {
    [photosView showPhotos:self];
}

- (void)butClick:(UIButton*)button {
    theRightButton = button;
    FDAlertView *alert = [[FDAlertView alloc] init];
    RBCustomDatePickerView * contentView=[[RBCustomDatePickerView alloc]init];
    contentView.delegate=self;
    contentView.frame = CGRectMake(0, 0, 320, 300);
    alert.contentView = contentView;
    [alert show];
}

-(void)endEdit {
    [self.view endEditing:true];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:true];
}

- (NSString*)collectData {
    if([taskName.textField.text isEqualToString:@""]) {
        return @"请输入任务名称";
    }
    if([taskDescribe.textView.text isEqualToString:@""]) {
        return @"请输入任务描述";
    }
    if([taskLocation.textField.text isEqualToString:@""]) {
        return @"请输入任务地点";
    }
    if([taskSignTime.time.currentAttributedTitle.string isEqualToString:@"请点击选择时间"]) {
        return @"请指定报名时间";
    }
    if([taskBeginTime.time.currentAttributedTitle.string isEqualToString:@"请点击选择时间"]) {
        return @"请指定开始时间";
    }
    if([taskEndTime.time.currentAttributedTitle.string isEqualToString:@"请点击选择时间"]) {
        return @"请指定截止时间";
    }
    if(subTaskArr.count != 0) {
        for(int i = 0; i<subTaskArr.count; i++) {
            Step3SubTask *subTask = subTaskArr[i];
            if([subTask.textField.text isEqualToString:@""] || [subTask.inputView.textView.text isEqualToString:@""]) {
                return @"请输入子任务描述和价值";
            }
            else {
                subTaskDescri[[@"子任务" stringByAppendingString:[NSString stringWithFormat:@"%d", i]]] = @{@"value": subTask.textField.text, @"describe": subTask.inputView.textView.text};
            }
        }
    }
    _data[@"name"] = taskName.textField.text;
    _data[@"describe"] = taskDescribe.textView.text;
    _data[@"address"] = taskLocation.textField.text;
    _data[@"lasttime"] = taskSignTime.time.currentAttributedTitle.string;
    _data[@"starttime"] = taskBeginTime.time.currentAttributedTitle.string;
    _data[@"overtime"] = taskEndTime.time.currentAttributedTitle.string;
    _data[@"subtasknum"] = subTaskNum.button.currentAttributedTitle.string;
    _data[@"subdescribe"] = subTaskDescri;
    //暂无
    _data[@"icontask"] = taskIcon.imageView.image;
    _data[@"industry"] = @"1";
    _data[@"realtask"] = @"1";
    return @"noerror";
}

- (void)nextStep {
    NSString *errorInfo = [self collectData];
    if([errorInfo isEqualToString:@"noerror"]) {
        ReleaseStep4ViewController *next = [[ReleaseStep4ViewController alloc] init];
        next.data = _data;
        [self.navigationController pushViewController:next animated:true];
    }
    else {
        [QYNotice showError:errorInfo toView:self.view];
        [QYNotice dismissWithDelay:3];
    }
}

- (void)selectSubTaskNum {
    pickNum = [[CLPickerView alloc] initWithFrame:CGRectMake(0, screenHeight, screenWidth, screenHeight/3)];
    [pickNum.selectBut addTarget:self action:@selector(changeNum) forControlEvents:UIControlEventTouchUpInside];
    [pickNum show];
}

- (void)changeNum {
    NSString *num = pickNum.contentTitle[[pickNum.picker selectedRowInComponent:0]];
    [subTaskNum.button setAttributedTitle:[[NSAttributedString alloc] initWithString:num attributes:@{NSForegroundColorAttributeName: TEXT_DETAIL_COLOR, NSFontAttributeName: [UIFont systemFontOfSize:14]}] forState:UIControlStateNormal];
    [pickNum dismiss];
    [self addSubTaskView:[num intValue]];
}

- (void)addSubTaskView:(int)num {
    if(num == 0) {
        for(int i = 0; i < subTaskArr.count; i++) {
            Step3SubTask *temp1 = subTaskArr[i];
            [temp1 removeFromSuperview];
        }
        [subTaskArr removeAllObjects];
        [self adjustScrollContent:subTaskNum.frame.origin.y + subTaskNum.frame.size.height];
    }
    else {
        for(int i = 0; i < subTaskArr.count; i++) {
            Step3SubTask *temp1 = subTaskArr[i];
            [temp1 removeFromSuperview];
        }
        [subTaskArr removeAllObjects];
        for(int i = 0; i < num; i++) {
            if(i == 0) {
                Step3SubTask *tempSubTask = [[Step3SubTask alloc] initWithTitle:@"子任务1描述:"];
                tempSubTask.layer.position = CGPointMake(screenWidth/2, subTaskNum.frame.origin.y + subTaskNum.frame.size.height + 5 + 51);
                tempSubTask.inputView.textView.tag = i;
                tempSubTask.inputView.textView.delegate = self;
                tempSubTask.textField.delegate = self;
                [scroll addSubview:tempSubTask];
                [subTaskArr addObject:tempSubTask];
            }
            else {
                Step3SubTask *temp = subTaskArr[i - 1];
                NSString *tit = @"子任务";
                tit = [tit stringByAppendingString:[NSString stringWithFormat:@"%d", i + 1]];
                tit = [tit stringByAppendingString:@"描述:"];
                Step3SubTask *tempSubTask = [[Step3SubTask alloc] initWithTitle:tit];
                tempSubTask.layer.position = CGPointMake(screenWidth/2, temp.frame.origin.y + temp.frame.size.height + 5 + 51);
                tempSubTask.inputView.textView.tag = i;
                tempSubTask.inputView.textView.delegate = self;
                tempSubTask.textField.delegate = self;
                [scroll addSubview:tempSubTask];
                [subTaskArr addObject:tempSubTask];
            }
        }
        Step3SubTask *temp = [subTaskArr lastObject];
        [self adjustScrollContent:temp.frame.origin.y + temp.frame.size.height];
    }
}

- (void)adjustScrollContent:(CGFloat)bottom {
    if(scroll.frame.size.height < bottom) {
        scroll.contentSize = CGSizeMake(scroll.frame.size.width, bottom);
    }
    else {
        scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height + 1);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma 代理方法

- (void)getTimeToValue:(NSString *)theTimeStr {
    NSLog(@"%@", theTimeStr);
    [theRightButton setAttributedTitle:[[NSAttributedString alloc] initWithString:theTimeStr attributes:@{NSForegroundColorAttributeName: TEXT_TITLE_COLOR, NSFontAttributeName: [UIFont systemFontOfSize:17]}] forState:UIControlStateNormal];
}

- (void)keyboardWillShow:(NSNotification*)notification {
    NSDictionary *dic = notification.userInfo;
    CGFloat keyboardHeight = [[dic objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    CGFloat adjust = textBottom - ([GZConst getScreenHeight] - keyboardHeight - 64);
    CGRect temp = scrollOrigin;
    if(adjust > 0) {
        temp.origin.y -= adjust;
        [UIView animateWithDuration:0.3 animations:^{
            scroll.frame = temp;
        }];
    }
    else {
        [UIView animateWithDuration:0.3 animations:^{
            scroll.frame = temp;
        }];
    }
}

- (void)keyboardWillHide:(NSNotification*)notification {
    [UIView animateWithDuration:0.3 animations:^{
        scroll.frame = scrollOrigin;
    }];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textBottom = textField.frame.origin.y + textField.frame.size.height + textField.superview.frame.origin.y - scroll.contentOffset.y;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if(textView.tag >= 0 && textView.tag < subTaskArr.count) {
        textBottom = textView.frame.origin.y + textView.frame.size.height + textView.superview.superview.frame.origin.y - scroll.contentOffset.y;
    }
    else {
        textBottom = textView.frame.origin.y + textView.frame.size.height + textView.superview.frame.origin.y - scroll.contentOffset.y;
    }
    return true;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self endEdit];
}

- (void)selectedPhotos:(NSArray<UIImage *> *)photos {
    taskIcon.imageView.image = photos[0];
}

@end
